package ChaiPiao;

import java.util.ArrayList;
import java.util.List;

public class Enumerator<ENUM_TYPE> {
    private List<Enumerable<ENUM_TYPE>> enumerableList;

    public Enumerator() {
        this.enumerableList = new ArrayList<>();
    }

    /************************************
     * methods
     **********************************/
    public void addEnumerable(Enumerable<ENUM_TYPE> enumerable) {
        this.enumerableList.add(enumerable);
    }

    public List<List<ENUM_TYPE>> enumerate() {
        List<List<ENUM_TYPE>> result = new ArrayList<>();
        List<ENUM_TYPE> enumerationSet = new ArrayList<>();
        for (int i = 0; i < enumerableList.size(); ++i) {
            enumerationSet.add(enumerableList.get(i).enumeration());
        }
        result.add(enumerationSet);
        boolean isOver = false;
        while (true) {
            enumerationSet = new ArrayList<>();
            ENUM_TYPE enumeration = null;
            for (int i = 0; i < enumerableList.size(); ++i) {
                if (i == 0) {
                    enumeration = enumerableList.get(i).enumeration();
                    if (enumeration == null) {
                        enumerableList.get(i + 1).enumeration();
                        enumerableList.get(i).reset();
                        enumeration = enumerableList.get(i).enumeration();
                    }
                    enumerationSet.add(enumeration);
                } else {
                    if (enumerableList.get(i).isEnumOver()) {
                        if (i == enumerableList.size() - 1) {
                            isOver = true;
                        } else {
                            enumerableList.get(i).reset();
                            enumeration = enumerableList.get(i).enumeration();
                            enumerationSet.add(enumeration);
                            enumerableList.get(i + 1).enumeration();
                        }
                    } else {
                        enumeration = enumerableList.get(i).getCurrent();
                        enumerationSet.add(enumeration);
                    }
                }
            }
            if (!isOver) {
                result.add(enumerationSet);
            } else {
                //枚举体重置。以免影响其他客户端引用的操作
                enumerableList.forEach((game) -> {
                    game.reset();
                });
                break;
            }
        }
        return result;
    }
}
